package com.efounder.chat.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.utils.luban.CompressionPredicate;
import com.efounder.utils.luban.Luban;
import com.efounder.utils.luban.OnRenameListener;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.FileUtils;
import com.utilcode.util.ImageUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

//import wseemann.media.FFmpegMediaMetadataRetriever;

public class ImageUtil {

    public static String userDir = Environment.getExternalStorageDirectory().getPath() +
            "/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID) + "/" + EnvironmentVariable.getProperty(CHAT_USER_ID) + "/";
    public static String chatDir = userDir + "chat/";
    private static String dirZone = userDir + "zone/";
    public static String chatpath = chatDir + "chatimage/";
    public static String encryptImgPath = chatDir + ".encryptImg/";
    public static String decryptImgPath = chatDir + ".decryptImg/";
    public static String amrpath = chatDir + "chatamr/";
    public static String videopath = chatDir + "chatvideo/";
    public static String CHATPICTRE = userDir + "picture/";//聊天页面保存的图片文件夹
    public static String ZONE_VIDEO_DIR = dirZone + "zoneVideo/";
    public static String scale;
    public static ACache mACache = ACache.get(AppContext.getInstance(), "cache_thumbnail");

    static {
        File file = new File(chatpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //检查chatimage 有没有忽略扫描
        File nomediaFile = new File(chatpath + ".nomedia");
        if (!nomediaFile.exists()) {
            try {
                nomediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        File file1 = new File(amrpath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        File file2 = new File(CHATPICTRE);
        if (!file2.exists()) {
            file2.mkdirs();
        }
        File file3 = new File(videopath);
        if (!file3.exists()) {
            file3.mkdir();
        }
        File file4 = new File(dirZone);
        if (!file4.exists()) {
            file4.mkdir();
        }
        File file5 = new File(videopath);
        if (!file5.exists()) {
            file5.mkdir();
        }
        File file6 = new File(encryptImgPath);
        if (!file6.exists()) {
            file6.mkdir();
        }
        File file7 = new File(decryptImgPath);
        if (!file7.exists()) {
            file7.mkdir();
        }
        //创建不扫描这个目录的文件
        File noMediaFile = new File(chatpath + ".nomedia");
        if (!noMediaFile.exists()) {
            try {
                noMediaFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //    private static FFmpegMediaMetadataRetriever fmmr;
//    private static MediaMetadataRetriever mmr;
    //图片大小优化

    public static Bitmap getBitmapFromPath(String path, int width, int height) {
        File dst = new File(path);
        String fileName = null;
        Bitmap bitmap = null;
        if (null != dst && dst.exists()) {
            fileName = dst.getName();
            System.out.println("文件名称：" + fileName);
            BitmapFactory.Options opts = null;
            if (width > 0 && height > 0) {
                opts = new BitmapFactory.Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(dst.getPath(), opts);
                // 计算图片缩放比例
                final int minSideLength = Math.min(width, height);
                opts.inSampleSize = computeSampleSize(opts, minSideLength,
                        width * height);
                opts.inJustDecodeBounds = false;
                opts.inInputShareable = true;
                opts.inPurgeable = true;
            }


            try {
                bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
                saveFile(bitmap, fileName);
                String qweString = chatpath + "/" + fileName;
                System.out.println(qweString);
                bitmap = BitmapFactory.decodeFile(qweString);
                return bitmap;
            } catch (IOException e) {
                System.out.println("保存失败");
                e.printStackTrace();
            }


        }
        return bitmap;
    }

    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
                .floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 压缩保存图片
     *
     * @param path
     * @param width
     * @param height
     */
    public static String saveNewImage(String path, int width, int height) {
        File dst = new File(path);
        String fileName = null;
        Bitmap bitmap = null;
        if (null != dst && dst.exists()) {
            try {
                fileName = dst.getName();
                System.out.println("文件名称：" + fileName);
                BitmapFactory.Options opts = null;
                if (width > 0 && height > 0) {
                    opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(dst.getPath(), opts);
                    //如果是长图，不进行压缩
                    if (opts.outWidth / opts.outHeight > 2 || opts.outHeight / opts.outWidth > 2) {
                        opts.inSampleSize = 1;
                        scale = opts.outWidth + ":" + opts.outHeight;

                        opts.inJustDecodeBounds = false;
                        opts.inInputShareable = true;
                        opts.inPurgeable = true;
                        //长图使用之前的
                        bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
                        bitmap = reviewPicRotate(bitmap, path);
                        saveFile(bitmap, fileName);
                        String qweString = chatpath + fileName;
                        System.out.println(qweString);

                    } else {
                        // 计算图片缩放比例
                        final int minSideLength = Math.min(width, height);
                        opts.inSampleSize = computeSampleSize(opts, minSideLength,
                                width * height);
                        int SWidth = opts.outWidth / opts.inSampleSize;
                        int SHeight = opts.outHeight / opts.inSampleSize;
                        scale = SWidth + ":" + SHeight;

                        //新的压缩算法 鲁班
                        final String finalFileName = fileName;
                        Luban.with(AppContext.getInstance())
                                .load(dst)
                                //不压缩的阈值，单位为K
                                .ignoreBy(100)
                                //缓存压缩图片路径
                                .setTargetDir(chatpath)
                                //压缩条件 不压缩gif
                                .filter(new CompressionPredicate() {
                                    @Override
                                    public boolean apply(String path) {
                                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                    }
                                })
                                //压缩后的文件名称
                                .setRenameListener(new OnRenameListener() {
                                    @Override
                                    public String rename(String filePath) {
                                        return finalFileName + ".pic";
                                    }
                                })

                                .get();
                        //chatpath + fileName + ".pic"

                        //新的压缩算法 Compressor
//                        new Compressor(AppContext.getInstance())
//                                .setMaxWidth(width)
//                                .setMaxHeight(height)
//                                .setQuality(80)
//                                .setCompressFormat(Bitmap.CompressFormat.JPEG)
//                                .setDestinationDirectoryPath(chatpath)
//                                .compressToFile(dst, fileName + ".pic");
                    }

                }

                int degree = ImageUtils.getBitmapDegree(dst.getPath());
                if (degree != 0) {
                    //图片被旋转 重新调整
                    String[] s = scale.split(":");
                    scale = s[1] + ":" + s[0];
                }

//                bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
//                bitmap = reviewPicRotate(bitmap, path);
//
//
//                saveFile(bitmap, fileName);
//                String qweString = chatpath + fileName;
//                System.out.println(qweString);


            } catch (Exception e) {
                System.out.println("保存失败");
                e.printStackTrace();
                return null;
            }
        }
        return scale;
    }

    /**
     * 压缩保存图片
     * 以前版本的图片压缩保存
     * @param path
     * @param width
     * @param height
     */
    public static String saveNewImageOld(String path, int width, int height) {
        File dst = new File(path);
        String fileName = null;
        Bitmap bitmap = null;
        if (null != dst && dst.exists()) {
            try {
                fileName = dst.getName();
                System.out.println("文件名称：" + fileName);
                BitmapFactory.Options opts = null;
                if (width > 0 && height > 0) {
                    opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(dst.getPath(), opts);
                    //如果是长图，不进行压缩
                    if (opts.outWidth / opts.outHeight > 2 || opts.outHeight / opts.outWidth > 2) {
                        opts.inSampleSize = 1;
                        scale = opts.outWidth + ":" + opts.outHeight;
                    } else {
                        // 计算图片缩放比例
                        final int minSideLength = Math.min(width, height);
                        opts.inSampleSize = computeSampleSize(opts, minSideLength,
                                width * height);
                        int SWidth = opts.outWidth / opts.inSampleSize;
                        int SHeight = opts.outHeight / opts.inSampleSize;
                        scale = SWidth + ":" + SHeight;
                    }
                    opts.inJustDecodeBounds = false;
                    opts.inInputShareable = true;
                    opts.inPurgeable = true;
                }

                int degree = ImageUtils.getBitmapDegree(dst.getPath());
                if (degree != 0) {
                    //图片被旋转 重新调整
                    String[] s = scale.split(":");
                    scale = s[1] + ":" + s[0];
                }

                bitmap = BitmapFactory.decodeFile(dst.getPath(), opts);
                bitmap = reviewPicRotate(bitmap, path);


                saveFile(bitmap, fileName);
                String qweString = chatpath + fileName;
                System.out.println(qweString);
                //bitmap =  BitmapFactory.decodeFile(qweString);

            } catch (Exception e) {
                System.out.println("保存失败");
                e.printStackTrace();
                return null;
            }
        }
        return scale;
    }

    /**
     * 获取图片文件的信息，是否旋转了90度，如果是则反转
     *
     * @param bitmap 需要旋转的图片
     * @param path   图片的路径
     */
    public static Bitmap reviewPicRotate(Bitmap bitmap, String path) {
        int degree = ImageUtils.getBitmapDegree(path);
        if (degree != 0) {
            Matrix m = new Matrix();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            // 旋转angle度
            m.setRotate(degree);
            // 从新生成图片
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
        }
        return bitmap;
    }

    /**
     * 得到图片的宽高信息
     */
    public static String getPicScale(String path) {
        File dst = new File(path);
        if (dst.exists()) {
            BitmapFactory.Options opts = null;
            opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(dst.getPath(), opts);
            int width = opts.outWidth;
            int height = opts.outHeight;
            scale = width + ":" + height;
        }
        return scale;
    }


    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveFile(Bitmap bm, String fileName) throws IOException {

        File dirFile = new File(chatpath);
        if (!dirFile.exists()) {

            dirFile.mkdirs();
        }

        File myCaptureFile = new File(chatpath + fileName + ".pic");
        if (myCaptureFile.exists()) {
            myCaptureFile.delete();
        }
        //   if (!myCaptureFile.exists()) {

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream
                (myCaptureFile));
        try {
            bm.compress(Bitmap.CompressFormat.JPEG, 85, bos);
        } catch (Exception e) {
            Toast.makeText(AppContext.getInstance(), "上传失败，请检查文件路径或类型", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        bos.flush();
        bos.close();
        System.out.println("保存成功");
        //  }
    }

    /**
     * 聊天页面保存聊天图片
     *
     * @param fileName
     * @param mBitmap
     */
    public static void saveMyBitmap(Context context, String fileName, Bitmap mBitmap) {
        File f = new File(CHATPICTRE + fileName + ".png");
        try {
            f.createNewFile();
        } catch (IOException e) {
            Log.e("ImageUtil", "在保存图片时出错");
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
//            ToastUtil.showToast(context, "图片已保存:" + CHATPICTRE
//                    + fileName + ".png");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 从路径中获取文件名
     *
     * @param pathandname
     * @return
     */
    public static String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        // int end=pathandname.lastIndexOf(".");
        // if(start!=-1 && end!=-1){
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }

    }

    /**
     * 将保存的图片在系统相册中显示
     */
    public static void galleryAddPic(String photoPath) {
        //屏蔽的方法无效不起作用
//        	    try {
//	        MediaStore.Images.Media.insertImage(AppContext.getInstance().getContentResolver(),
//                    photoPath, photoPath.substring(photoPath.lastIndexOf("/"),photoPath.length()), null);
//	    } catch (Exception e) {
//	        e.printStackTrace();
//	    }
        //获取文件mimetyoe
        String mimeType1 = FileUtil.getMimeType(photoPath);
        //扫描这个文件,刷新相册
        MediaScannerConnection.scanFile(AppContext.getInstance()
                , new String[]{photoPath}
                , new String[]{(mimeType1)}, null);
        //发送广播
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(photoPath);
        //不能用下面这行，无效
//        Uri contentUri = UriUtils.getUriForFile(f);
        Uri contentUri = Uri.fromFile(f);

        mediaScanIntent.setData(contentUri);
        AppContext.getInstance().sendBroadcast(mediaScanIntent);
    }


    //////////////////////////////////////////////////////////////////////////////////////

    /**
     * 从本地获取视频缩略图
     *
     * @param path
     * @param fileName
     * @return
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
    public static Bitmap getVideoThumbnail(String path, String fileName) {
        String filePath = path + File.separator + fileName;
        return getVideoThumbnail(filePath);
    }

    public static Bitmap getVideoThumbnail(String path) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(path);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 从网络获取视频缩略图
     *
     * @param url
     * @param width
     * @param height
     * @return
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static Bitmap getVideoThumbnail(String url, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14 && url != null && (url.startsWith("http") || url.startsWith("https"))) {
                Map map = new HashMap<String, String>();
                retriever.setDataSource(url, new HashMap<String, String>());
                bitmap = retriever.getFrameAtTime();
//                bitmap = createBitmap(url);
//                bitmap = createVideoThumbnail(url);

            } else {
                retriever.setDataSource(url);
                bitmap = retriever.getFrameAtTime();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
//                fmmr.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        if (bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }


    /**
     * 根据url获取视频的缩略图
     *
     * @param url
     * @return
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
    public static Bitmap createVideoThumbnail(String url) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
//            if (filePath.startsWith("http://")
//                    || filePath.startsWith("https://")
//                    || filePath.startsWith("widevine://")) {
            retriever.setDataSource(url, new Hashtable<String, String>());
//            } else {
//                retriever.setDataSource(filePath);
//            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
            ex.printStackTrace();
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
            ex.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
                ex.printStackTrace();
            }
        }

        if (bitmap == null) return null;

//        if (kind == MediaStore.Images.Thumbnails.MINI_KIND) {
//            // Scale down the bitmap if it's too large.
//            int width = bitmap.getWidth();
//            int height = bitmap.getHeight();
//            int max = Math.max(width, height);
//            if (max > 512) {
//                float scale = 512f / max;
//                int w = Math.round(scale * width);
//                int h = Math.round(scale * height);
//                bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
//            }
//        } else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND) {
//            bitmap = ThumbnailUtils.extractThumbnail(bitmap,
//                    96,
//                    96,
//                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
//        }
        return bitmap;
    }

    private static Bitmap createBitmap(String url) {
//        fmmr = new FFmpegMediaMetadataRetriever();
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String path = "http://panserver.solarsource.cn:9692/panserver/files/c232c3da-6817-4ee0-930a-985c672fa224/download";
//        String path = "http://baobab.wdjcdn.com/145076769089714.mp4";
        mmr.setDataSource(url, new Hashtable<String, String>());
        Bitmap bitmap = mmr.getFrameAtTime();
        /*if (bitmap != null) {
            Bitmap b2 = fmmr.getFrameAtTime(10000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            if (b2 != null) {
                bitmap = b2;
            }
            return bitmap;
        }*/
        return bitmap;
    }

    public static void saveBitmap(Bitmap bitmap, String path, String fileName) {
        String savePath = path + File.separator + fileName + ".pic";
        File file = new File(savePath);
        //bitmap-->byte[]
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
        byte[] values = byteArrayOutputStream.toByteArray();
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(values);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static void saveCacheVideoThumbnail(Bitmap bitmap, String fileName) {
        //使用ACache进行缓存
        mACache.put(fileName, bitmap);
    }

    public static Bitmap getBitmap(String path, String fileName) {
        RandomAccessFile randomAccessFile = null;
        try {
            File cacheFile = new File(path, fileName + ".pic");
            if (!cacheFile.exists())
                return null;
            randomAccessFile = new RandomAccessFile(cacheFile, "r");
            byte[] bytes = new byte[(int) randomAccessFile.length()];
            randomAccessFile.read(bytes);
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Bitmap getBitmap(String path) {
        RandomAccessFile randomAccessFile = null;
        try {
            File cacheFile = new File(path);
            if (!cacheFile.exists())
                return null;
            randomAccessFile = new RandomAccessFile(cacheFile, "r");
            byte[] bytes = new byte[(int) randomAccessFile.length()];
            randomAccessFile.read(bytes);
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotateDegree);
        Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);
        return rotaBitmap;
    }

    public static Bitmap getCacheVideoThumbnail(String fileName) {
        //使用ACache获取缓存
        return mACache.getAsBitmap(fileName);
    }

    //获取file 直接给glide 加载
    public static File geCacheVideoThumbnailFile(String fileName) {
        //使用ACache获取缓存
        return mACache.getFileFromCache(fileName);
    }

    /**
     * 判断是否是gif动图
     *
     * @param file
     * @return
     */
    public static boolean isGifFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            int[] flags = new int[5];
            flags[0] = inputStream.read();
            flags[1] = inputStream.read();
            flags[2] = inputStream.read();
            flags[3] = inputStream.read();
            inputStream.skip(inputStream.available() - 1);
            flags[4] = inputStream.read();
            inputStream.close();
            return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 保存网络图片，使用glide
     *
     * @param url
     * @param mHandler
     */
    public static void saveNetWorkImage(String url, final Handler mHandler) {
        File picPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        try {
            if (url.startsWith("file://")) {//本地图片
//                Toast.makeText(AppContext
//                        .getInstance(), "本地图片", Toast.LENGTH_SHORT).show();
                String text = url.replace("file://", "")
                        .replace(".pic", "");

                String newFileName = System.currentTimeMillis() + text.substring(text.lastIndexOf("."), text.length());
                File newFile = new File(picPath.getAbsolutePath(), newFileName);
                ;
                copyAndSaveFile(new File(url.replace("file://", "")), newFile, mHandler);
            } else {
                if (new File(url).exists()) {
                    Toast.makeText(AppContext
                            .getInstance(), "图片已保存至" + url.substring(0, url.lastIndexOf("/")) + "目录下", Toast.LENGTH_SHORT).show();
                } else {
                    if (!picPath.exists()) {
                        picPath.mkdirs();
                    }

                    String fileName = PansoftCloudUtil.getPansoftCloudFileId(url) + ".png";
                    String fileName2 = PansoftCloudUtil.getPansoftCloudFileId(url) + ".gif";
                    final File file = new File(picPath.getAbsolutePath(), fileName);
                    final File file2 = new File(picPath.getAbsolutePath(), fileName2);
                    //如果gif 和png 图片都不存在 表示图片确实不存在
                    if (!file.exists() && !file2.exists()) {

                        Glide.with(ActivityUtils.getTopActivity()).asFile().load(url).into(new SimpleTarget<File>() {
                            @Override
                            public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                                copyAndSaveFile(resource, file, mHandler);
                            }
                        });


                    } else {
                        //图片已存在
                        mHandler.sendEmptyMessage(3);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //保存失败
            mHandler.sendEmptyMessage(2);
        }
    }

    private static void copyAndSaveFile(@NonNull File resource, File file, Handler mHandler) {
        FileUtils.copyFile(resource, file,
                new FileUtils.OnReplaceListener() {
                    @Override
                    public boolean onReplace() {
                        //存在同名文件是否替换
                        return true;
                    }
                });

        if (ImageUtil.isGifFile(file)) {
            String newPath = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("."));
            File gifFile = new File(newPath + ".gif");
            file.renameTo(gifFile);
            // 通知图库更新（注意这里传的是gifFile）
            ImageUtil.galleryAddPic(gifFile.getAbsolutePath());
        } else {
            // 通知图库更新
            ImageUtil.galleryAddPic(file.getAbsolutePath());
        }
        //保存成功
        mHandler.sendEmptyMessage(1);
    }

}
